import * as fs from "fs";
import * as os from "os";
import * as vscode from "vscode";

import { DOMAIN, FORUMS } from "./util/apis";
import adrequest from "./util/adrequest";

function success(decodedData: any): void {
  let mdData = '';
  for (let i = 0; i < decodedData.length; i++) {
    const catagory = decodedData[i];
    const forums = catagory.forums;
    mdData += `# ${catagory.name}\r\n`;
    for (let j = 0; j < forums.length; j++) {
      const forum = forums[j];
      mdData += `## id:${forum.id} ${forum.name}\r\n`;
    }
  }

  fs.writeFile(os.tmpdir() + '/目录.md', mdData, 'utf-8', (err) => {
    if (err) {
      console.error(err);
      throw err;
    }
    console.log(`${os.tmpdir()}/目录.md 写入成功`);
    const a = vscode.Uri.file(os.tmpdir() + '/目录.md');
    vscode.window.showTextDocument(a);
    vscode.window.showInformationMessage("目录打开成功！");
  });
}

export default function forums() {
  adrequest(DOMAIN + FORUMS, success, (e: Error) => {
    vscode.window.showErrorMessage(e.message);
  });
}